package com.gmail.at.service.jpa;

import java.math.BigDecimal;
import java.util.List;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gmail.at.dao.PassengerDAO;
import com.gmail.at.dao.RoleDAO;
import com.gmail.at.dao.TicketDAO;
import com.gmail.at.model.Passenger;
import com.gmail.at.model.Role;
import com.gmail.at.model.Schedule;
import com.gmail.at.model.Ticket;
import com.gmail.at.service.TicketService;
import com.google.common.collect.Lists;

@Service("ticketService")
@Repository
@Transactional
public class TicketServiceImpl implements TicketService {
	
	@Autowired
	private TicketDAO ticketDAO;
	
	@Autowired
	private PassengerDAO passengerDAO;
	
	@Autowired
	private RoleDAO roleDAO;

	@Override
	@Transactional(readOnly=true)
	public List<Ticket> findAll() {
		return Lists.newArrayList(ticketDAO.findAll());
	}

	@Override
	@Transactional(readOnly=true)
	public Ticket findById(Integer id) {
		return ticketDAO.findOne(id);
	}


	@Override
	public void delete(Ticket ticket) {
		ticketDAO.delete(ticket);

	}

	@Override
	public String buy(Schedule schedule) {
		Passenger passenger = null;
		if (schedule.getTickets().size() < schedule.getTrain().getPlaces()) {
			List<Ticket> allTickets = schedule.getTickets();
			try {
				User user = (User) SecurityContextHolder.getContext()
						.getAuthentication().getPrincipal();
				passenger = passengerDAO.findByLogin(user.getUsername());
			} catch (Exception e) {
				return "Sorry, if you want to buy a ticket you should login";
			}
			Role role = roleDAO.findByPassenger(passenger);
			if (passenger == null) {
				return "Sorry, if you want to buy a ticket you should login";
			}
			if (!(role.getAuthority().equals("ROLE_USER"))) {
				return "Adimns couldn't buy tickets";
			}
			for (int i = 0; i < allTickets.size(); i++) {
				if (allTickets.get(i).getPassenger().equals(passenger)) {
					return "Sorry, but you already have the ticket for this train"; 
				}
			}
			DateTime currentTime = DateTime.now();
			currentTime.plusMinutes(10);
			if (schedule.getDateOfDeparture().compareTo(currentTime) <= 0) {
				return "It's too late, train will go in 10 minutes. Sorry!";
			}
			Ticket ticket = new Ticket();
			ticket.setPassenger(passenger);
			ticket.setSchedule(schedule);
			ticket.setPrice(BigDecimal.valueOf(500));
			if (ticketDAO.save(ticket) != null) {
				return "ok";
			} 
		} else {
			return "Sorry but there are no available places on this train";
		}
		return "Some problemes happend";
	}

	@Override
	public String sell(Ticket ticket) {
		Passenger passenger = null;
		try {
			User user = (User) SecurityContextHolder.getContext()
					.getAuthentication().getPrincipal();
			passenger = passengerDAO.findByLogin(user.getUsername());
		} catch (Exception e) {
			return "Sorry, if you want to sell a ticket you should login";
		}
		if (ticket.getPassenger() == passenger) {
			this.delete(ticket);
			return "You have successfully sold the ticket!";
		}
		return "Internal problems, refresh the page.";
	}

}
